package me.zingon.WebSocket.ws;

import me.zingon.WebSocket.tools.VideoTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

/**
 * Created by ZTC on 12/26/2016.
 */
public class VideoWS extends AbstractWebSocketHandler{

    @Autowired
    VideoTool videoTool;

    int i=0;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String[] p=session.getUri().getQuery().split("=");
        if(p[1].equals("W"))
            videoTool.addWatcher(session);
        session.getAttributes().put("add","end");
        StringBuilder sb=new StringBuilder();
        session.getAttributes().put("buffer",sb);
        System.out.println(session.getId()+" add");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String base64Img=message.getPayload();
        StringBuilder sb= (StringBuilder) session.getAttributes().get("buffer");
        String add= (String) session.getAttributes().get("add");
        if(base64Img.equals("end")) {
            add="end";
            session.getAttributes().put("add", "end");
            videoTool.send2All(sb.substring(5));
            sb.delete(0,sb.length());
        }
        if(base64Img.equals("start")) {
            add="start";
            session.getAttributes().put("add", "start");
        }
        if(add.equals("start")){
            sb.append(base64Img);
        }
        //System.out.println(i+++" "+base64Img);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        videoTool.rmWatcher(session);
        System.out.println(session.getId()+" close");
    }
}
